package com.ems.service.impl.Invigilate.room;
import com.ems.dao.Invigilate.room.ExaminationPaperDao;
import com.ems.pojo.Invigilate.room.*;
import com.ems.pojo.questions.Choose;
import com.ems.pojo.questions.FillBanks;
import com.ems.pojo.questions.Judgment;
import com.ems.pojo.questions.answer.ChooseAnswer;
import com.ems.pojo.questions.answer.FillBanksAnswer;
import com.ems.pojo.questions.answer.JudgmentAnswer;
import com.ems.pojo.user.User;
import com.ems.service.Invigilate.room.*;
import com.ems.service.supers.questions.ChooseService;
import com.ems.service.supers.questions.FillService;
import com.ems.service.supers.questions.JudgmentService;
import com.ems.utils.Tools;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.*;

/**
 * @Auther: 伟伟
 * @Date: 2020/2/18
 * @Description: 描述
 * @Version: 1.0
 */
@Service("examinationService")
public class ExaminationServiceImpl implements ExaminationService {
    @Autowired
    private ExaminationPaperDao examinationPaperDao;

    @Autowired
    @Qualifier("chooseService")
    private ChooseService chooseService;

    @Autowired
    @Qualifier("judgmentService")
    private JudgmentService judgmentService;

    @Autowired
    @Qualifier("fillService")
    private FillService fillService;

    @Autowired
    @Qualifier("testQuestionsService")
    private TestQuestionsService testQuestionsService;

    @Autowired
    @Qualifier("testScoreResultService")
    private TestScoreResultService testScoreResultService;

    @Autowired
    @Qualifier("testResultService")
    private TestResultService testResultService;

    @Autowired
    @Qualifier("roomPaperService")
    private RoomPaperService roomPaperService;


    @Override
    public void addExaminationPaper(ExaminationPaper examinationPaper) {

        //存储试题的基本信息
        examinationPaper.setEp_time(Tools.getTime()); //试题创建时间

        //获取生成试题的详情信息
        List<TestQuestions> testQuestionsList = examinationPaper.getTestQuestionsList();

        if(testQuestionsList.size() > 0){
            examinationPaper.setSb_id(getQuestionInfoClass(testQuestionsList.get(0).getTq_question_info()).getSb_id());
        }

        examinationPaperDao.addExaminationPaper(examinationPaper);

        TestQuestions testQuestions = null;

        for(int i = 0;i < testQuestionsList.size();i ++){

            testQuestions = testQuestionsList.get(i);
            if(testQuestions.getTq_fraction() == 0){
                continue;
            }

            testQuestions.setEp_id(examinationPaper.getEp_id());

            if(testQuestions.getTq_type() == 1){ //单选

                danChooseQuestion(testQuestions);

            }else if(testQuestions.getTq_type() == 2){ //多选

                duoChooseQuestion(testQuestions);

            }else if(testQuestions.getTq_type() == 3){ //判断

                judgmentQuestion(testQuestions);

            }else if(testQuestions.getTq_type() == 4){ //填空

                fillQuestion(testQuestions);

            }else if(testQuestions.getTq_type() == 5){ //简答

            }

        }

    }


    //单选
    private void danChooseQuestion(TestQuestions testQuestions){
        String questionInfoStr = testQuestions.getTq_question_info();

        QuestionInfo questionInfo = getQuestionInfoClass(questionInfoStr);

        Set<Integer> chooseIds = new HashSet<>(); //存储选择题的id

        List<Choose> chooseList = chooseService.getChooseBySbAndId(questionInfo.getSb_id(),1,questionInfo.getQuestion_Num());

        if(chooseList != null && chooseList.size() > 0){
            for(int i = 0;i < chooseList.size();i ++){
                chooseIds.add(chooseList.get(i).getCh_id());
            }
        }

        String chooseIdStr = null;
        if(chooseIds.size() > 0){
            chooseIdStr = org.apache.commons.lang.StringUtils.join(chooseIds,":");
        }

        testQuestions.setTq_questions_id(chooseIdStr);

        //存储选择的选择题信息
        testQuestionsService.addTestQuestions(testQuestions);

    }

    //多选
    private void duoChooseQuestion(TestQuestions testQuestions){
        String questionInfoStr = testQuestions.getTq_question_info();

        QuestionInfo questionInfo = getQuestionInfoClass(questionInfoStr);

        Set<Integer> chooseIds = new HashSet<>(); //存储选择题的id


        List<Choose> chooseList = chooseService.getChooseBySbAndId(questionInfo.getSb_id(),2,questionInfo.getQuestion_Num());

        if(chooseList != null && chooseList.size() > 0){
            for(int i = 0;i < chooseList.size();i ++){
                chooseIds.add(chooseList.get(i).getCh_id());
            }
        }


        String chooseIdStr = null;
        if(chooseIds.size() > 0){
            chooseIdStr = org.apache.commons.lang.StringUtils.join(chooseIds,":");
        }

        testQuestions.setTq_questions_id(chooseIdStr);

        //存储选择的选择题信息
        testQuestionsService.addTestQuestions(testQuestions);

    }

    //判断
    private void judgmentQuestion(TestQuestions testQuestions){
        String questionInfoStr = testQuestions.getTq_question_info();

        QuestionInfo questionInfo = getQuestionInfoClass(questionInfoStr);


        Set<Integer> judgmentIds = new HashSet<>(); //存储判断题的id

        List<Judgment> judgmentList = judgmentService.getJudgmentBySbAndId(questionInfo.getSb_id(),questionInfo.getQuestion_Num());

        if(judgmentList != null && judgmentList.size() > 0){
            for(int i = 0;i < judgmentList.size();i ++){
                judgmentIds.add(judgmentList.get(i).getJ_id());
            }
        }

        String judgmentStr = null;
        if(judgmentIds.size() > 0){
            judgmentStr = org.apache.commons.lang.StringUtils.join(judgmentIds,":");
        }

        testQuestions.setTq_questions_id(judgmentStr);

        //存储随机生成的判断题
        testQuestionsService.addTestQuestions(testQuestions);

    }

    //填空
    private void fillQuestion(TestQuestions testQuestions){
        String questionInfoStr = testQuestions.getTq_question_info();

        QuestionInfo questionInfo = getQuestionInfoClass(questionInfoStr);

        Set<Integer> fillBankIds = new HashSet<>(); //存储填空题的id

        List<FillBanks> fillBanksList = fillService.getFillBanksBySbAndId(questionInfo.getSb_id(),questionInfo.getQuestion_Num());

        if(fillBanksList != null && fillBanksList.size() > 0){
            for(int i = 0;i < fillBanksList.size();i ++){
                fillBankIds.add(fillBanksList.get(i).getFb_id());
            }
        }

        String fillStr = null;
        if(fillBankIds.size() > 0){
            fillStr = org.apache.commons.lang.StringUtils.join(fillBankIds,":");
        }

        testQuestions.setTq_questions_id(fillStr);

        testQuestionsService.addTestQuestions(testQuestions);

    }

    private QuestionInfo getQuestionInfoClass(String str){
        JSONObject jsonObject = JSONObject.fromObject(str);
        QuestionInfo questionInfo = (QuestionInfo) JSONObject.toBean(jsonObject,QuestionInfo.class);
        return questionInfo;
    }

    //获取试题信息
    @Override
    public List<ExaminationPaper> getExaminationPaper(Map<String, Object> map,User user) {
        String ep_name = (String) map.get("ep_name");
        int sb_id = (int)map.get("sb_id");

        List<ExaminationPaper> examinationPaperList = examinationPaperDao.getExaminationPaper(ep_name, user.getId(),sb_id);

        return examinationPaperList;
    }

    //根据id查询试题
    @Override
    public ExaminationPaper getExaminationPaperById(ExaminationPaper examinationPaper) {
        //查询试题信息
        ExaminationPaper examinationPaper1 = examinationPaperDao.getExaminationPaperById(examinationPaper.getEp_id());

        TestQuestions testQuestions = null;
        List<Integer> idsList = null;

        for(int i = 0;i < examinationPaper1.getTestQuestionsList().size();i ++){

            testQuestions = examinationPaper1.getTestQuestionsList().get(i);
            idsList = getQuestionIds(testQuestions.getTq_questions_id());

            if(idsList.size() <= 0){
                continue;
            }

            if(testQuestions.getTq_type() == 1){ //单选
                testQuestions.setQuestionList(chooseService.getChooseByIdsList(idsList));

            }else if(testQuestions.getTq_type() == 2){ //多选
                testQuestions.setQuestionList(chooseService.getChooseByIdsList(idsList));

            }else if(testQuestions.getTq_type() == 3){ //判断
                testQuestions.setQuestionList(judgmentService.getJudgmentByIdsList(idsList));

            }else if(testQuestions.getTq_type() == 4){ //填空
                testQuestions.setQuestionList(fillService.getFillBanksByIdsList(idsList));

            }
        }

        return examinationPaper1;
    }

    //根据id查询试题(非答案)
    @Override
    public ExaminationPaper getNoAnswerExaminationPaperById(ExaminationPaper examinationPaper) {
        //获取试题信息
        ExaminationPaper examinationPaper1 = getExaminationPaperById(examinationPaper);

        //去除其中的答案信息
        TestQuestions testQuestions = null;
        List<Choose> chooseList = null;
        List<Judgment> judgmentList = null;
        List<FillBanks> fillBanksList = null;
        for(int i = 0;i < examinationPaper1.getTestQuestionsList().size();i ++){
            testQuestions = examinationPaper1.getTestQuestionsList().get(i);
            if(testQuestions.getTq_type() == 1 || testQuestions.getTq_type() == 2){
                chooseList = (List<Choose>)testQuestions.getQuestionList();
                for(int j = 0;j < chooseList.size();j ++){
                    List<ChooseAnswer> chooseAnswerList = chooseList.get(j).getChooseAnswerList();
                    for(int n = 0;n < chooseAnswerList.size();n ++){
                        chooseAnswerList.get(n).setCa_answer(null);
                    }
                }
            }else if(testQuestions.getTq_type() == 3){
                judgmentList = (List<Judgment>)testQuestions.getQuestionList();
                for(int j = 0;j < judgmentList.size();j ++){
                    judgmentList.get(j).setJudgmentAnswer(new JudgmentAnswer());
                }
            }else if(testQuestions.getTq_type() == 4){
                fillBanksList = (List<FillBanks>)testQuestions.getQuestionList();
                for(int j = 0;j < fillBanksList.size();j ++){

                    String AnsStr = fillBanksList.get(j).getFillBanksAnswer().getFba_answer();
                    String arrayAnswer[] = AnsStr.split("-");
                    for(int n = 0;n < arrayAnswer.length;n ++){
                        arrayAnswer[n] = "*";
                    }
                    fillBanksList.get(j).setFillBanksAnswer(new FillBanksAnswer(org.apache.commons.lang.StringUtils.join(arrayAnswer,"-")));
                }
            }

        }

        return examinationPaper1;
    }

    //获取保存题目id的集合
    private List<Integer> getQuestionIds(String idsStr){

        String idsArray[] = idsStr.split(":");
        List<Integer> list = new ArrayList<>();

        if(idsArray != null && idsArray.length > 0){
            for(int i = 0;i < idsArray.length; i ++){
               list.add(Integer.parseInt(idsArray[i]));
            }
        }
        return list;
    }

    //根据id修改试题信息
    @Override
    public void updateExaminationById(ExaminationPaper examinationPaper) {
        examinationPaperDao.updateExaminationById(examinationPaper);
    }

    //根据id删除试题信息
    @Override
    public void deleteExaminationById(List<ExaminationPaper> examinationPaperList) {
        if(examinationPaperList != null && examinationPaperList.size() > 0){
            ExaminationPaper examinationPaper = null;
            for(int i = 0;i < examinationPaperList.size();i ++){
                examinationPaper = examinationPaperList.get(i);
                //删除考场中考卷的信息
                //1. 查询考场中考卷信息
                List<RoomPaper> roomPaperList = roomPaperService.getRoomPaperByEpId(examinationPaper.getEp_id());

                //2. 查询该考卷的考试信息
                for(int j = 0;j < roomPaperList.size();j ++){
                    testScoreResultService.deleteTestScoreResultByRpId(roomPaperList.get(j).getRp_id());
                }
                //删除考卷
                examinationPaperDao.deleteExaminationById(examinationPaper);

            }
        }
    }

    //改卷
    @Override
    public void rewinding(ExaminationPaper examinationPaper) {

        TestScoreResult testScoreResult = new TestScoreResult();
        List<TestResult> testResultList = new ArrayList<>();

        TestQuestions testQuestions = null;
        for(int i = 0;i < examinationPaper.getTestQuestionsList().size();i ++){
            testQuestions = examinationPaper.getTestQuestionsList().get(i);

            if(testQuestions.getTq_type() == 1){ //单选题
                List<Choose> chooseList = (List<Choose>)testQuestions.getChooseList();
                //获取每道题的分数
                int score = testQuestions.getTq_fraction() / chooseList.size();
                int sumScore = 0;
                String resultStr = "";

                for(int j = 0;j < chooseList.size();j ++){
                     //获取答案
                     Choose choose = chooseList.get(j);


                     ChooseAnswer chooseAnswer = chooseService.getAnswer(choose.getCh_id());
                     String s = chooseList.get(j).getChooseAnswerList().get(0).getCa_answer();
                     if(s != null){
                         resultStr += s;
                     }else{
                         resultStr += "*";
                     }
//                     if(!chooseAnswer.getCa_answer().equals(chooseList.get(j).getChooseAnswerList().get(0).getCa_answer())){
//                         testQuestions.setTq_fraction(testQuestions.getTq_fraction() - score);
//                     }
                    if(chooseAnswer.getCa_answer().equals(chooseList.get(j).getChooseAnswerList().get(0).getCa_answer())){
                        sumScore += score;
                    }
                }

                //int sb_id, int tr_type, int tr_questions_id, String tr_result, float tr_score
//                testResultList.add(new TestResult(examinationPaper.getSb_id(),1,testQuestions.getTq_id(),resultStr,testQuestions.getTq_fraction()));
                testQuestions.setTq_fraction(sumScore);
                testResultList.add(new TestResult(examinationPaper.getSb_id(),1,testQuestions.getTq_id(),resultStr,sumScore));

            }else if(testQuestions.getTq_type() == 2){ //多选题
                List<Choose> chooseList = (List<Choose>)testQuestions.getChooseList();
                //获取每道题的分数
                int score = testQuestions.getTq_fraction() / chooseList.size();
                int sumScore = 0;


                String tr_result = "";

                for(int j = 0;j < chooseList.size();j ++){
                    //获取答案
                    List<ChooseAnswer> chooseAnswerList = chooseService.getAnswerList(chooseList.get(j).getCh_id());
                    //用户选择的答案
                    List<ChooseAnswer> chooseAnswerList1 = chooseList.get(j).getChooseAnswerList();
                    if(chooseAnswerList.size() != chooseAnswerList1.size()){
                        testQuestions.setTq_fraction(testQuestions.getTq_fraction() - score);
                    }else{
                        String ans = ""; //正确答案
                        for(int n = 0;n < chooseAnswerList.size();n ++){
                           ans += chooseAnswerList.get(n).getCa_answer();
                        }

                        for(int n = 0;n < chooseAnswerList1.size();n ++){
                            tr_result += chooseAnswerList1.get(n).getCa_answer();
                           boolean status = ans.contains(chooseAnswerList1.get(n).getCa_answer());
//                           if(!status){
//                               testQuestions.setTq_fraction(testQuestions.getTq_fraction() - score);
//                               break;
//                           }
                            if(status){
                                sumScore += score;
                                break;
                            }
                        }
                        testQuestions.setTq_fraction(sumScore);
                }
                    if(j < chooseList.size() - 1){
                        tr_result += "-";
                    }
                }

                //int sb_id, int tr_type, int tr_questions_id, String tr_result, float tr_score
//                testResultList.add(new TestResult(examinationPaper.getSb_id(),2,testQuestions.getTq_id(),tr_result,testQuestions.getTq_fraction()));
                testResultList.add(new TestResult(examinationPaper.getSb_id(),2,testQuestions.getTq_id(),tr_result,sumScore));

            }else if(testQuestions.getTq_type() == 3){ //判断题
                List<Judgment> judgmentList = (List<Judgment>)testQuestions.getJudgmentList();
                //获取每道题的分数
                int score = testQuestions.getTq_fraction() / judgmentList.size();
                int sumScore = 0;
                String tr_result = "";

                for(int j = 0;j < judgmentList.size();j ++){
                    //获取正确答案
                    JudgmentAnswer judgmentAnswer = judgmentService.getAnswer(judgmentList.get(j).getJ_id());
                    tr_result += judgmentList.get(j).getJudgmentAnswer().getJa_answer();
//                    if(!judgmentAnswer.getJa_answer().equals(judgmentList.get(j).getJudgmentAnswer().getJa_answer())){
//                        testQuestions.setTq_fraction(testQuestions.getTq_fraction() - score);
//                    }
                    if(judgmentAnswer.getJa_answer().equals(judgmentList.get(j).getJudgmentAnswer().getJa_answer())){
                        sumScore += score;
                    }
                }

                //int sb_id, int tr_type, int tr_questions_id, String tr_result, float tr_score
//                testResultList.add(new TestResult(examinationPaper.getSb_id(),3,testQuestions.getTq_id(),tr_result,testQuestions.getTq_fraction()));
                testQuestions.setTq_fraction(sumScore);
                testResultList.add(new TestResult(examinationPaper.getSb_id(),3,testQuestions.getTq_id(),tr_result,sumScore));


            }else if(testQuestions.getTq_type() == 4){ //填空题
                List<FillBanks> fillBanksList = (List<FillBanks>)testQuestions.getFillBanksList();

                //获取每道题的分数
                int score = testQuestions.getTq_fraction() / fillBanksList.size();
                String tr_result = "";
                float score2 = 0;

                for(int j = 0;j < fillBanksList.size();j ++){
                    //获取正确答案
                    FillBanksAnswer fillBanksAnswer = fillService.getAnswer(fillBanksList.get(j).getFb_id());
                    String fillBanksAnswerArr[] = fillBanksAnswer.getFba_answer().split("-");

                    //考生答案
                    FillBanksAnswer fillBanksAnswer1 = fillBanksList.get(j).getFillBanksAnswer();
                    String fillBanksAnswer1Arr[] = fillBanksAnswer1.getFba_answer().split("-");

                    tr_result += fillBanksAnswer1.getFba_answer();
                    if(j < fillBanksList.size() - 1){
                        tr_result += ":";
                    }

                    //获取每空的分数
                    float score1 = score / fillBanksAnswerArr.length;
                    for(int n = 0;n < fillBanksAnswerArr.length;n ++){
                        if(fillBanksAnswerArr[n].equals(fillBanksAnswer1Arr[n])){
                            fillBanksAnswer1.setScore(fillBanksAnswer1.getScore() + score1);
                            score2 += score1;
                        }
                    }

                }
                //int sb_id, int tr_type, int tr_questions_id, String tr_result, float tr_score
                testResultList.add(new TestResult(examinationPaper.getSb_id(),4,testQuestions.getTq_id(),tr_result,score2));
            }
        }

        testScoreResult.setRp_id(examinationPaper.getRp_id());
        testScoreResult.setId(examinationPaper.getId());
        testScoreResult.setTsr_text_time(Tools.getTime());
        float count = 0;
        for(int i = 0;i < testResultList.size();i ++){
            count += testResultList.get(i).getTr_score();
        }
        testScoreResult.setTsr_score(count);

        //存储考生考试信息
        testScoreResultService.addTestScoreResult(testScoreResult);

        for(int i = 0;i < testResultList.size();i ++){
            testResultList.get(i).setTsr_id(testScoreResult.getTsr_id());
            testResultService.addTestResult(testResultList.get(i));
        }

    }

    @Override
    public void deleteExaminationByEpId(int ep_id) {
        //删除test_questions信息
        testQuestionsService.deleteByEpId(ep_id);
        //删除examination_paper信息
        examinationPaperDao.deleteByEpId(ep_id);
    }
}
